package org.hjj.design.auth.domain.request;

import java.net.URL;

/**
 * handle api request
 *
 * @author:何嘉俊
 * @date:2021/5/7
 */
public class ApiRequest {
    private String originUrl;

    private String token;

    private String appId;

    private long timestamp;

    public ApiRequest(String originUrl, String token, String appId, long timestamp) {
        this.originUrl = originUrl;
        this.token = token;
        this.appId = appId;
        this.timestamp = timestamp;
    }

    /**
     * create {@link ApiRequest} from a full url
     * @param url
     * @return
     * @throws RuntimeException: when url is invalid
     */
    public static ApiRequest createFromFulUrl(String url) {
        if (null == url || url.length() == 0) {
            throw new RuntimeException("Url is invalid");
        }

        URL originUrl;
        try {
            originUrl = new URL(url);
        } catch (Exception e) {
            throw new RuntimeException("Url is invalid");
        }

        String preUrl = originUrl.getHost();
        String sufUrl = originUrl.getQuery();

        String[] urlParams = sufUrl.split("&");
        if (urlParams.length < 3) {
            throw new RuntimeException("Url is invalid");
        }

        String token = null, appId = null;
        long timestamp = 0L;
        for (String urlParam : urlParams) {
            String[] kv = urlParam.split("=", 2);
            String key = kv[0], value = kv[1];
            if (key.startsWith("token")) {
                token = value;
            } else if (key.startsWith("appId")) {
                appId = value;
            } else if (key.startsWith("timestamp")) {
                try {
                    timestamp = Long.valueOf(value);
                } catch (Exception e) {
                    throw new RuntimeException("Url is invalid");
                }
            }
        }

        return new ApiRequest(preUrl, token, appId, timestamp);
    }

    public String getOriginalUrl() {
        return originUrl;
    }

    public String getToken() {
        return token;
    }

    public String getAppId() {
        return appId;
    }

    public long getTimestamp() {
        return timestamp;
    }
}
